package com.jian.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jian.project.annotation.AuthCheck;
import com.jian.project.common.BaseResponse;
import com.jian.project.common.DeleteRequest;
import com.jian.project.common.ErrorCode;
import com.jian.project.common.ResultUtils;
import com.jian.project.constant.CommonConstant;
import com.jian.project.exception.BusinessException;
import com.jian.project.model.dto.dbinterface.DbInterfaceAddRequest;
import com.jian.project.model.dto.dbinterface.DbInterfaceApiRequest;
import com.jian.project.model.dto.dbinterface.DbInterfaceQueryRequest;
import com.jian.project.model.dto.dbinterface.DbInterfaceUpdateRequest;
import com.jian.project.model.dto.post.IdRequest;
import com.jian.project.model.dto.user.ModeApiRequest;
import com.jian.project.model.entity.DbInterface;
import com.jian.project.model.entity.User;
import com.jian.project.model.enums.InterfaceStatusEnum;
import com.jian.project.service.DbInterfaceService;
import com.jian.project.service.UserService;
import com.jian.springbootdemosdk.JApiClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.jian.project.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 帖子接口
 *
 * @author jian
 */
@RestController
@RequestMapping("/DbInterface")
@Slf4j
public class DbInterfaceController {

    @Resource
    private DbInterfaceService dbInterfaceService;

    @Resource
    private UserService userService;

    @Resource
    private JApiClient jApiClient;

    // region 增删改查

    /**
     * 创建
     *
     * @param dbInterfaceAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addDbInterface(@RequestBody DbInterfaceAddRequest dbInterfaceAddRequest, HttpServletRequest request) {
        if (dbInterfaceAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        DbInterface dbInterface = new DbInterface();
        BeanUtils.copyProperties(dbInterfaceAddRequest, dbInterface);
        // 校验
        dbInterfaceService.validDbInterface(dbInterface, true);
        User loginUser = userService.getLoginUser(request);
        dbInterface.setUserId(loginUser.getId());
        boolean result = dbInterfaceService.save(dbInterface);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        long newDbInterfaceId = dbInterface.getId();
        return ResultUtils.success(newDbInterfaceId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteDbInterface(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        DbInterface oldDbInterface = dbInterfaceService.getById(id);
        if (oldDbInterface == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldDbInterface.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = dbInterfaceService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新
     *
     * @param dbInterfaceUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateDbInterface(@RequestBody DbInterfaceUpdateRequest dbInterfaceUpdateRequest,
                                                   HttpServletRequest request) {
        if (dbInterfaceUpdateRequest == null || dbInterfaceUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        DbInterface dbInterface = new DbInterface();
        BeanUtils.copyProperties(dbInterfaceUpdateRequest, dbInterface);
        // 参数校验
        dbInterfaceService.validDbInterface(dbInterface, false);
        User user = userService.getLoginUser(request);
        long id = dbInterfaceUpdateRequest.getId();
        // 判断是否存在
        DbInterface oldDbInterface = dbInterfaceService.getById(id);
        if (oldDbInterface == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        if (!oldDbInterface.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = dbInterfaceService.updateById(dbInterface);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<DbInterface> getDbInterfaceById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        DbInterface dbInterface = dbInterfaceService.getById(id);
        return ResultUtils.success(dbInterface);
    }

    /**
     * 获取列表（仅管理员可使用）
     *
     * @param dbInterfaceQueryRequest
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @GetMapping("/list")
    public BaseResponse<List<DbInterface>> listDbInterface(DbInterfaceQueryRequest dbInterfaceQueryRequest) {
        DbInterface dbInterfaceQuery = new DbInterface();
        if (dbInterfaceQueryRequest != null) {
            BeanUtils.copyProperties(dbInterfaceQueryRequest, dbInterfaceQuery);
        }
        QueryWrapper<DbInterface> queryWrapper = new QueryWrapper<>(dbInterfaceQuery);
        List<DbInterface> dbInterfaceList = dbInterfaceService.list(queryWrapper);
        return ResultUtils.success(dbInterfaceList);
    }

    /**
     * 分页获取列表
     *
     * @param dbInterfaceQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<DbInterface>> listDbInterfaceByPage(DbInterfaceQueryRequest dbInterfaceQueryRequest, HttpServletRequest request) {
        if (dbInterfaceQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        DbInterface dbInterfaceQuery = new DbInterface();
        BeanUtils.copyProperties(dbInterfaceQueryRequest, dbInterfaceQuery);
        long current = dbInterfaceQueryRequest.getCurrent();
        long size = dbInterfaceQueryRequest.getPageSize();
        String sortField = dbInterfaceQueryRequest.getSortField();
        String sortOrder = dbInterfaceQueryRequest.getSortOrder();
        String description = dbInterfaceQuery.getDescription();
        // description 需支持模糊搜索
        dbInterfaceQuery.setDescription(null);
        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<DbInterface> queryWrapper = new QueryWrapper<>(dbInterfaceQuery);
        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        Page<DbInterface> dbInterfacePage = dbInterfaceService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(dbInterfacePage);
    }

    /**
     * 开启接口
     *
     * @param idRequest
     * @return
     */
    @PostMapping("/online")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> onlineInterface(@RequestBody IdRequest idRequest) {
        if (idRequest == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        DbInterface dbInterface = new DbInterface();
        dbInterface.setId(idRequest.getId());
        // 判断是否存在
        DbInterface oldDbInterface = dbInterfaceService.getById(dbInterface.getId());
        if (oldDbInterface == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        dbInterface.setStatus(InterfaceStatusEnum.ONLINE.getValue());
        boolean result = dbInterfaceService.updateById(dbInterface);
        return ResultUtils.success(result);
    }

    /**
     * 关闭接口
     *
     * @param idRequest
     * @return
     */
    @PostMapping("/offline")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> offlineInterface(@RequestBody IdRequest idRequest) {
        if (idRequest == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        DbInterface dbInterface = new DbInterface();
        dbInterface.setId(idRequest.getId());
        // 判断是否存在
        DbInterface oldDbInterface = dbInterfaceService.getById(dbInterface.getId());
        if (oldDbInterface == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        dbInterface.setStatus(InterfaceStatusEnum.OFFLINE.getValue());
        boolean result = dbInterfaceService.updateById(dbInterface);
        return ResultUtils.success(result);
    }

    /**
     * 模拟接口测试
     */
    @PostMapping("/demo_api")
    @AuthCheck(anyRole = {"user", "admin"})
    public BaseResponse<String> demoApiInterface(@RequestBody ModeApiRequest modeApiRequest) {
        String s = jApiClient.getName(modeApiRequest.getName(), modeApiRequest.getInterfaceId());
        return ResultUtils.success(s);
    }

    /**
     * 页面接口调用开发
     */
    @PostMapping("/invoke_api")
    @AuthCheck(anyRole = {"user", "admin"})
    public BaseResponse<?> invokeApi(@RequestBody DbInterfaceApiRequest dbInterfaceApiRequest, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null)
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);

        return ResultUtils.success(dbInterfaceService.invokeApi(dbInterfaceApiRequest, user));
    }

}
